<?php
#                                                                                 
# author: Cody Sorgenfrey                                       
# (c)2013 South Hill Calvary Chapel                                               
#                                                                                 
include_once("database_info.php");
include_once("common.php");
include_once("../common.php");
$title = "MySql Editor";
$meta_key=null;
$meta_desc=null;
print_html_head($title ,$meta_key,$meta_desc);
print_java_head(NULL);
?>
	<style>
		@keyframes blinky{
			from {background-color: #eeeeee;}
			to {background-color: #c4d7e5;}
		}
		@-webkit-keyframes blinky{
			from {background-color: #eeeeee;}
			to {background-color: #c4d7e5;}
		}
		div.body{
			width: 98%;
			margin-top: 20px;
		}
		div.menubar{
			display: none;
		}
		h2.page_title{
			display: none;
		}
		#loginBox{
			width: 200px;
			height: 140px;
			text-align: center;
			padding-top: 30px;
			margin-right: auto;
			margin-left: auto;
			border-radius: 5px;
			box-shadow: 1px 1px 5px black;
		}
		#loginError{
			color: red;
		}
		#noPass{
			margin-top: 10px;
			font-size: 80%;
			text-align: center;
		}
		div#tablePicker{
			width: 14%;
			padding-right: 1%;
		}
		div#selection{
			width: 81%;
			padding-left: 1%;
		}
		div#tablePicker,
		div#selection{
			display: inline-table;
			vertical-align: top;
		}
		div#tables{
			width: 94%;
			min-height: 200px;
			overflow: scroll;
			background-color: #eeeeee;
			box-shadow: inset 1px 1px 7px black;
			border-radius: 5px;
			padding: 3%;
		}
		.header{
			margin-top: 0px;
			font-family: Gnuolane;
			font-size: 20pt;
		}
		div.window{
			position: absolute;
			top: 35%;
			bottom: 35%;
			left: 35%;
			right: 35%;
			padding: 2%;
			z-index: 2000;
			box-shadow: 2px 2px 20px black;
			background-color: #eeeeee;
			display: none;
		}
		div#searchHolder{
			width: 400px;
			min-height: 165px;
			max-height: 200px;
			-webkit-transform: translateX(-300%);
			-webkit-transition-duration: 1s;
			-webkit-backface-visibility: hidden;
		}
		div#search{
			-webkit-transform: rotateZ(-45deg);
			float: right;
			font-family: sans-serif;
			color: #a2a2a2;
			font-size: 20pt;
			cursor: pointer;
			margin-top: -42px;
		}
		div#addRow{
			float: right;
			font-family: sans-serif;
			color: #a2a2a2;
			font-size: 20pt;
			cursor: pointer;
			margin-top: -39px;
			margin-right: 30px;
		}
		input#searchField{
			width: 200px;
			color: black;
			cursor: text;
			margin-right: 10px;
		}
		button#searchButton{
			float: right;
		}
		div#currentTable{
			overflow: scroll;
		}
		table{
			-webkit-touch-callout: none;
		    -webkit-user-select: none;
		    -khtml-user-select: none;
		    -moz-user-select: moz-none;
		    -ms-user-select: none;
		    user-select: none;
		}
		tr{
			border-bottom: 1px solid silver;
		}
		tr.selected>td{
			background-color: #c4d7e5;
		}
		td{
			background-color: white;
			height: 60px;
			max-width: 200px;
			white-space: nowrap;
			overflow: hidden;
			text-overflow: ellipsis;
			padding: 10px;
		}
		td.editMode{
			max-width: 600px;
		}
		textarea{
			max-width: 600px;
		}
		div#rowFunctions{
			width: 100%;
			padding: 0px;
			margin-top: 5px;
			display: none;
		}
		div.functionButton{
			display: table-cell;
			padding: 10px;
			vertical-align: middle;
			cursor: pointer;
			background-color: #eeeeee;
			border-right: 2px solid white;
			border-left: 2px solid white;
			white-space: nowrap;
		}
		div#applyEdits{
			display: none;
			animation-name: blinky;
			animation-duration: 1s;
			animation-iteration-count: infinite;
			animation-direction: alternate;
			animation-timing-function: linear;
			-webkit-animation-name: blinky;
			-webkit-animation-duration: 1s;
			-webkit-animation-iteration-count: infinite;
			-webkit-animation-direction: alternate;
			-webkit-animation-timing-function: linear;
		}
		div#rowCount{
			text-align: right;
			width: 100%;
			cursor: default;
		}
		div.table{
			width: 96%;
			padding: 2%;
			margin-bottom: 2px;
			border-radius: 5px;
			box-shadow: 1px 1px 3px black;
			background-color: white;
			text-overflow: ellipsis;
			white-space: nowrap;
			overflow: hidden;
			cursor: pointer;
		}
		div.table.selected{
			background-color: #c4d7e5;
		}
		span.tableName{
			font-family: Gnuolane;
			font-size: 10pt;
		}
	</style>
	<script type="text/javascript">
		var tables;
		$(document).ready(function(){
			$("div#currentTable").css("max-width", $("div#selection").width()); //dynamically set css
			$("div#currentTable").css("max-height", ($(document).height() - 230));
			$("div#tables").css("max-height", ($(document).height() - 210));
			loadTables();
		});
		function loadTables(){
			$.post("tables.php", {
				key: "<?echo crypt("He1sR1sen");?>"
			}, function(res){
				if (res.length > 0){
					tables = res.split("|row|");
					for (x in tables){
						tables[x] = tables[x].split("|cell|");
					}
					printTables();
				} else {
					alert("Error getting tables.");
				}
			});
		}
		function printTables(){
			var tableNames = new Array;
			for (x in tables){
				var newTable = "<div class='table'>";
				newTable += "<span class='tableName'>" + tables[x][0] + "</span";
				newTable += "</div>";
				$("#tables").append(newTable);
				$("div.table:last").data("data", tables[x]);
			}
			sortTablesByName();
			$(".table").click(function(e){
				var tar;
				if ($(e.target).is("div.table")){
					tar = e.target;
				} else {
					tar = $(e.target).parents("div.table");
				}
				selectTable(tar);
			});
		}
		function sortTablesByName(){
			var names = new Array;
			$("div.table").each(function(){
				names.push($(this).text().toUpperCase());
				$(this).attr("name", $(this).text().toUpperCase());
			});
			names.sort();
			for (x=0;x<names.length;x++){
				var thisElem = $("div.table[name='"+ names[x] +"']");
				$("div#tables").append(thisElem);
				$(thisElem).removeAttr("name");
			}
		}
		function selectTable(tar){
			$("div.table").removeClass("selected");
			$(tar).addClass("selected");
			$("div#currentHeader").text($(tar).text());
			$("div#rowFunctions").hide();
			$("table").text("Loading...");
			resetSearchWindow();
 			loadSelectedTable(tar, "id", $("#sortOrder").children(":selected").val(), $("#showOnly").val(), "", "");
		}
		function loadSelectedTable(tar, orderVar, directionVar, limitVar, searchFieldVar, searchStringVar){
			$.post("data.php",{
				key: "<?echo crypt("He1sR1sen");?>",
				table: $(tar).text().replace(" ", ""),
				order: orderVar,
				direction: directionVar,
				limit: limitVar,
				searchField: searchFieldVar,
				searchString: searchStringVar,
			}, function(res){
				$("table").text("");
				if (res.search("empty") == 0) {
					$("table").append("Selected table is empty");
				} else if (res.length > 0){
					res = res.split("|row|");
					for (x in res){
						res[x] = res[x].split("|cell|");
						printRow(res[x]);
					}
					$("tr").click(function(e){
						delegateClick(e);
					});
					$("tr").dblclick(function(e){
						editMode();
					});
				} else {
					alert("Error getting table.");
				}
			});
		}
		function printRow(row){
			$("table").append("<tr></tr>");
			var data = $("div.table.selected").data("data");
			for (x=0;x<row.length;x++){
				$("tr:last").append("<td></td>");
				$("td:last").text(row[x]);
				$("td:last").attr("title", data[x+1]); //gives us tooltips
			}
		}
		function delegateClick(e){
			var tar = ($(e.target).is("tr")) ? e.target : $(e.target).parents("tr");
			var rowsSelected = $("tr.selected").length;
			if (rowsSelected == 0){
				if ($(tar).hasClass("selected")){
					removeFromSelection(tar);
				} else {
					addToSelection(tar);
				}
			} else if (e.shiftKey) {
				if ($(tar).hasClass("selected")){
					removeFromSelection(tar);
				} else {
					addToSelection(tar);
				}
			} else {
				clearSelection();
				addToSelection(tar);
			}
		}
		function addToSelection(tar){
			cancelEditMode();
			$(tar).addClass("selected");
			var rowsSelected = $("tr.selected").length;
			if (rowsSelected == 1) $("div#rowFunctions").show();
			$("div#rowCount").text("Selected "+rowsSelected+" row"+((rowsSelected > 1) ? "s" : "")+".");
		}
		function removeFromSelection(tar){
			cancelEditMode();
			$(tar).removeClass("selected");
			var rowsSelected = $("tr.selected").length;
			if (rowsSelected == 0) $("div#rowFunctions").hide();
			$("div#rowCount").text("Selected "+rowsSelected+" row"+((rowsSelected > 1) ? "s" : "")+".");
		}
		function clearSelection(){
			cancelEditMode();
			$("tr.selected").removeClass("selected");
			$("div#rowFunctions").hide();
		}
		function editMode(){
			$("td").addClass("editMode");
			$("div#applyEdits").css("display", "table-cell");
			$("tr.selected").each(function(){
				$(this).unbind();
				$(this).children("td:not(td:first)").each(function(){
					$(this).data("oldVal", $(this).text());
					$(this).html("<textarea style='width:"+$(this).width()+"px;'>"+ $(this).text() +"</textarea>");
				});
			});
		}
		function applyEdits(){
			$("td").removeClass("editMode");
			$("div#applyEdits").hide();
			$("tr.selected").each(function(){
				$(this).children("td:not(td:first)").each(function(){
					var curCell = this;
					if ($(curCell).children("textarea").length == 0){
						alert("Error, row not in edit mode.");
						return 0;
					}
					var val = $(curCell).children("textarea").val();
					var oldVal = $(curCell).data("oldVal");
					if (val != oldVal){
						$(curCell).text("Saving...");
						$.post("updateRow.php", {
							key: "<?echo crypt("He1sR1sen");?>",
							table: $("div.table.selected").text(),
							id: $(curCell).siblings(":first").text(),
							col: $(curCell).attr("title"),
							value: val
						}, function(res){
							if (res.search("Updated") < 0){
								alert("Error updating rows");
								$(curCell).text(oldVal);
							} else {
 								$(curCell).text(val);
 								$(curCell).data("oldVal", val);
							}
						});
					} else {
						$(curCell).text(oldVal);
					}
				});
				$(this).unbind();
				$(this).dblclick(function(){
					editMode();
				});
				$(this).click(function(e){
					delegateClick(e);
				});
			});
		}
		function cancelEditMode(){
			$("td").removeClass("editMode");
			$("div#applyEdits").hide();
			$("tr.selected").each(function(){
				$(this).children("td:not(td:first)").each(function(){
					$(this).text($(this).data("oldVal"));
				});
				$(this).unbind();
				$(this).dblclick(function(){
					editMode()
				});
				$(this).click(function(e){
					delegateClick(e);
				});
			});
		}
		function toggleSearch(){
			if ($("#searchHolder").css("display") == "none"){
				$("#searchHolder").show();
				setTimeout(function(){
					$("#searchHolder").css("-webkit-transform", "translateX(0%)");
				}, 1);
			} else {
				$("#searchHolder").css("-webkit-transform", "translateX(300%)");
				setTimeout(function(){
					$("#searchHolder").hide();
					$("#searchHolder").css("-webkit-transform", "translateX(-300%)");
				}, 1000);
			}
		}
		function searchCurrentTable(){
			toggleSearch();
			loadSelectedTable($(".table.selected"), $("#orderCol").children(":selected").text(), $("#sortOrder").children(":selected").val(), $("#showOnly").val(), $("#searchCol").children(":selected").text(), $("#searchField").val());
		}
		function resetSearchWindow(){
			var data = $(".table.selected").data("data");
			$("select#searchCol, select#orderCol").children().remove();
			$("#searchField").val("");
			for (x=1;x<data.length;x++){
				$("select#searchCol, select#orderCol").append("<option>"+data[x]+"</option>");
			}
		}
		function duplicateSelected(){
			$("tr.selected").each(function(){
				var curRow = $(this);
				var cellText = new Array('');
				$(curRow).children("td:not(td:first)").each(function(){
					cellText.push($(this).text());
				});
				$.post("addRow.php", {
					key: "<?echo crypt("He1sR1sen");?>",
					cols: cellText.join("|col|"),
					table: $(".table.selected").text()
				}, function(res){
					if (res.search("Success") >= 0){
						res = res.split(".")[1];
						var newRow = $(curRow).clone();
						$(newRow).children("td:first").text(res);
						$(newRow).insertAfter($(curRow));
						removeFromSelection($(newRow));
					} else {
						alert("Error duplicating rows.");
					}
				});
			});
		}
		function deleteSelected(){
			$("tr.selected").each(function(){
				var curRow = $(this);
				$.post("delete.php", {
					key: "<?echo crypt("He1sR1sen");?>",
					id: $(curRow).children("td:first").text(),
					table: $(".table.selected").text()
				}, function(res){
					if (res.search("Deleted") >= 0){
						removeFromSelection($(curRow));
						$(curRow).remove();
					} else {
						alert("Error deleting rows.");
					}
				});
			});
		}
		function addRow(){
			var tableData = $(".table.selected").data("data");
			if (!tableData) return 0;
			$.post("addRow.php", {
				key: "<?echo crypt("He1sR1sen");?>",
				table: $(".table.selected").text()
			}, function(res){
				if (res.search("Success") >= 0){
					res = res.split(".");
					res.shift();
					for (x=0;x<(tableData.length-2);x++){
						res.push("");	
					}
					printRow(res);
					clearSelection();
					addToSelection($("tr:last"));
					editMode();
					$("#currentTable").scrollTop($("table").innerHeight());
				} else {
					alert(res);
				}
			});
		}
	</script>
<?
begin_body();
page_title_no_content($title);
$value = crypt("He1sR1sen");
if ($_POST['pass'] == "He1sR1sen"){
	?>
	<script type="text/javascript">
		document.cookie = "mysqlAdmin=<?echo $value;?>";
		document.location = document.location;
	</script>
	<?
} else if (!empty($_POST['pass'])){
	?>
	<script type="text/javascript">
		document.location.search = "?loginError=Incorrect+Password";
	</script>
	<?
}
if ($_COOKIE['mysqlAdmin'] != crypt("He1sR1sen", $_COOKIE['mysqlAdmin'])){
	?>
	<div id='loginBox'>
	<form method="post">
	<h3>Password</h3><br>
	<input name='pass' type="password" id='loginPassword'><br><br>
	<button>Login</button><br>
	<p id="loginError"><?echo $_GET['loginError']?></p>
	</form>
	</div>
	<p id='noPass'>Do you need the password? <a href="mailto:webservant@southhillcalvary.org?subject=Password%20for%20directory">Contact the Webservant</a></p>
	<?
	end_page_title();
	end_body();
	die();
}
?>
			<div id="tablePicker">
				<div id="tables"></div>
			</div>
			<div id="selection">
				<div class="header" id="currentHeader">No table selected...</div>
				<div id="search" onclick="toggleSearch();">⚲</div>
				<div id="addRow" onclick="addRow()">+</div>
				<div id="addRowHolder" class="window">
					<h4 class="header">Add Row</h4>
					<hr>
					<div id="addRowCols"></div>
					<button id="searchButton">Add</button>
				</div>
				<div id="searchHolder" class="window">
					<h4 class="header">Search</h4>
					<hr>
					<select id="searchCol"></select>
					<input type="text" id="searchField" placeholder="Search Current Table" />
					<br><br>
					<select id="orderCol"></select>
					<select id="sortOrder">
						<option value="DESC">Descending</option>
						<option value="ASC">Ascending</option>
					</select>
					<br><br>
					Show: <input id="showOnly" type="number" value="25" />
					<br>
					<button id="searchButton" onclick="searchCurrentTable()">Search</button>
				</div>
				<div id="rowFunctions">
					<div class="functionButton" onclick="applyEdits()" id="applyEdits">Apply</div>
					<div class="functionButton" onclick="editMode()">Edit</div>
					<div class="functionButton" onclick="duplicateSelected()">Duplicate</div>
					<div class="functionButton" onclick="deleteSelected()">Delete</div>
					<div class="functionButton" onclick="addToSelection($('tr'));">Select All</div>
					<div class="functionButton" onclick="clearSelection()">Cancel</div>
					<div class="functionButton" id="rowCount"></div>
				</div>
				<hr>
				<div id="currentTable">
					<table></table>
				</div>
			</div>
<?
end_page_title();
end_body();
?>